<template>
  <div class="app-container">
    <div class="tab-Toggle">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="表格数据" name="first">
          <div class="filter-container">
            <div class="filter-left" style="display: flex">
              <el-input v-model="searchKey" placeholder="工时所有者/项目名称/工时名称" style="width: 250px; margin-right: 10px"
                class="filter-item" @keyup.enter.native="handleFilter" @input="handleFilter" />

              <treeselect style="width: 250px;margin-right: 10px" v-model="value" :multiple="false"
                :options="rootOptions" :disable-branch-nodes="false" :limit="1" placeholder="选择部门查询" @select="onSelect"
                @input="oninput" @deselect="onDeselect" />
              <el-date-picker style="width: 300px;" v-model="pikerTime" type="daterange" range-separator="至"
                start-placeholder="开始日期" end-placeholder="结束日期" @change="onChangePiker" format="yyyy-MM-dd"
                value-format="yyyy-MM-dd">
              </el-date-picker>
            </div>
            <div class="filter-right">
              <el-button icon="el-icon-download" type="primary" @click="downloadFile">
                批量导出
              </el-button>
            </div>
          </div>
          <el-table :data="pageList" border stripe fit highlight-current-row v-loading="listLoading" style="width: 100%"
            :span-method="objectSpanMethod">
            <el-table-column type="index" label="序号" width="80" align="center" />
            <el-table-column prop="user_nick" label="工时所有者" align="center">
            </el-table-column>
            <el-table-column prop="projects_name" label="项目名称" align="center" :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column prop="start_time" label="工时开始日期" align="center">
            </el-table-column>
            <el-table-column prop="end_time" label="工时结束日期" align="center">
            </el-table-column>
            <el-table-column prop="work_title" label="填报单名称" align="center" :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column prop="work_amount" label="工时数量" align="center">
            </el-table-column>
            <el-table-column label="创建时间" width="200px" align="center">
              <template slot-scope="{ row }">
                <span>{{ row.created_at | formate }}</span>
              </template>
            </el-table-column>
            <el-table-column label="修改时间" width="200px" align="center">
              <template slot-scope="{ row }">
                <span>{{ row.updated_at | formate }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="remarks" label="备注" align="center" :show-overflow-tooltip="true">
            </el-table-column>
          </el-table>
          <pagination v-show="total > 0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize"
            @pagination="getPageList" />
        </el-tab-pane>
        <el-tab-pane label="图表数据" name="second">
          <div class="collect-chart">
            <div>
              <el-date-picker @change="handleChangeDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd" v-model="value1"
                type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
              </el-date-picker>
            </div>
            <div style="margin: 0 15px 0">
              <treeselect style="width: 250px" v-model="deptIds" :multiple="false" :options="rootOptions"
                :disable-branch-nodes="false" :limit="1" placeholder="选择部门查询" @input="oninputChart"
                @deselect="onDeselect" />
            </div>
            <div style="
                width: 200px;
                height: 38px;
                display: flex;
                align-items: center;
                margin-right: 10px;
              ">
              <el-switch @change="handleSwitch" v-model="switchValue" active-color="#13ce66" inactive-color="#ff4949"
                active-text="按项目查询" inactive-text="按部门查询">
              </el-switch>
            </div>
          </div>
          <div class="my-charts" ref="myChart" style="width: 1200px; height: 700px"></div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>
<script>
import {
  getWorkingPageAdmin,
  downloadAdminWorkingFile,
  getChartsData,
} from "@/api/workingHours";
import { checkUserToken, getDataByCode } from "@/api/user";
import waves from "@/directive/waves"; // waves directive
import { curentTime } from "@/filters/index";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import { getToken } from "@/utils/auth"; // get token from cookie
import axios from "axios";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "Order",
  components: { Pagination, Treeselect },
  directives: { waves },
  filters: {
    formate(date) {
      return curentTime(date);
    },
  },
  data() {
    return {
      // 订单数据
      pageList: [],
      // 订单总数
      total: 0,
      // 加载
      listLoading: true,
      // 查询条件
      listQuery: {
        pageNum: 1,
        pageSize: 10,
      },
      searchKey: "",
      searchKeyName: "",
      deptId: "",
      // 部门
      deptDate: [],
      rootOptions: [],
      value: null,
      rowSpanArr: [],
      activeName: "first",
      deptIds: null,
      value1: [
        this.handleGetData().Format("yyyy-MM-dd"),
        new Date().Format("yyyy-MM-dd"),
      ],
      switchValue: true,
      chartsXdata: [],
      seriesData: [],
      pikerTime: [] //选择日期时间
    };
  },
  async created() {
    await this.getPageList();
    this.getRootModels();
  },
  mounted() { },
  methods: {
    // 时间筛选
    async onChangePiker() {
      if (this.pikerTime) {
        this.listQuery.startTime = this.pikerTime[0]
        this.listQuery.endTime = this.pikerTime[1]
      }else{
        this.listQuery.startTime = ''
        this.listQuery.endTime = ''
      }
      await this.getPageList();
    },
    // 按需查询
    async handleFilter() {
      this.listQuery.searchKey = this.searchKey;
      this.listQuery.pageNum = 1;
      await this.getPageList();
    },

    // 查询列表
    async getPageList() {
      try {
        const res = await getWorkingPageAdmin(this.listQuery);
        this.total = res.data.total;
        this.handleTableData(res.data.lists);
        this.pageList = res.data.lists;
        this.listLoading = false;
      } catch (error) {
        console.log(error);
      }
    },
    // 批量导出
    async downloadFile() {
      checkUserToken().then((res) => {
        let baseUrl = `${process.env.VUE_APP_SERVER_URL}/admin/working/downloadAdminWorkingFile?timestamp=1`;
        if (this.searchKey) {
          baseUrl += `&searchKey=${this.searchKey}`;
        }
        if (this.listQuery.deptId) {
          baseUrl += `&deptId=${this.listQuery.deptId}`;
        } 
         if (this.pikerTime.length && this.pikerTime.length == 2) {
          baseUrl += `&startTime=${this.pikerTime[0]}&endTime=${this.pikerTime[1]}`;
        } 
        if (res.data) {
          axios({
            method: "get",
            url: baseUrl,
            headers: {
              "Content-type": "application/json;charset:utf-8;",
              "x-morefunoa-access-token": getToken(), //认证或授权
            },
            responseType: "blob",
          })
            .then((res) => {
              const blob = new Blob([res.data]);
              let year = new Date().getFullYear();
              let month = new Date().getMonth() + 1;
              let day = new Date().getDate();
              let time = year + "-" + month + "-" + day;
              const fileName = `工时汇总${time}.xlsx`;
              if ("download" in document.createElement("a")) {
                // 非IE下载
                const elink = document.createElement("a");
                elink.download = fileName;
                elink.style.display = "none";
                elink.href = URL.createObjectURL(blob);
                document.body.appendChild(elink);
                elink.click();
                URL.revokeObjectURL(elink.href); // 释放URL 对象
                document.body.removeChild(elink);
              } else {
                // IE10+下载
                navigator.msSaveBlob(blob, fileName);
              }
            })
            .catch((err) => {
              console.log(err);
            });
        }
      });
    },

    getRootModels() {
      //初始化数据 只加载根节点
      getDataByCode({ code: "DeptsUserTree" }).then((res) => {
        if (!res || !res.success || !res.data.DeptsUserTree)
          return this.$message({
            message: "获取部门树列表报错",
            type: "error",
          });
        const lists = this.dealTreeData(res.data.DeptsUserTree.dept_lists);
        this.rootOptions = lists;
      });
    },

    /**
     * 轮询处理树形结构列表
     */
    dealTreeData(tagArr) {
      let modeArr = [];
      for (let i = 0; i < tagArr.length; i++) {
        const item = tagArr[i];
        let modeInfo = {};
        modeInfo.id = item.dept_id;
        modeInfo.label = item.name;
        if (item.dept_lists && item.dept_lists.length) {
          modeInfo.children = this.dealTreeData(item.dept_lists);
        }
        modeArr.push(modeInfo);
      }
      return modeArr;
    },

    onSelect(node) {
      // console.log(node)
    },

    oninput(val) {
      if (val == undefined) {
        this.listQuery.deptId = "";
      } else {
        this.listQuery.deptId = val;
      }
      this.listLoading = true;
      this.handleFilter();
    },

    oninputChart(val) {
      this.handleFilterChart();
    },

    onDeselect(node) {
      // console.log(node, "Deselect");
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 1 || columnIndex === 2) {
        const rowSpan = this.rowSpanArr[rowIndex];
        return {
          rowspan: rowSpan, //行
          colspan: 1, //列
        };
      }
    },
    /**
     * 分析每一列，找出相同的
     * @param data
     */
    // 这里只放了部分代码,除了加了个if,其他代码和上面的一样
    // 获取相同名称的个数 tableData: 表格的数据, projectName: 确定相同的参数
    handleTableData(tableData) {
      let rowSpanArr = [],
        position = 0;
      for (let [index, item] of tableData.entries()) {
        if (index == 0) {
          rowSpanArr.push(1);
          position = 0;
        } else {
          if (item.projects_name == tableData[index - 1].projects_name) {
            rowSpanArr[position] += 1; //项目名称相同，合并到同一个数组中
            rowSpanArr.push(0);
          } else {
            rowSpanArr.push(1);
            position = index;
          }
        }
      }
      this.rowSpanArr = rowSpanArr;
    },

    // 切换tab
    handleClick() {
      if (this.activeName == "second") {
        this.handleFilterChart();
      }
    },

    handleSwitch() {
      this.handleFilterChart();
    },

    handleGetData() {
      var today = new Date();
      var weekDay = today.getDay(); // 获取当前日期是星期几
      var firstDay = new Date(
        today.getTime() - (weekDay - 1) * 24 * 60 * 60 * 1000
      ); // 计算当前日期周的第一天
      return firstDay;
    },

    handleChangeDate() {
      this.handleFilterChart();
    },

    // 查询图表信息
    handleFilterChart() {
      if (this.value1) {
        this.chartsXdata = [];
        this.seriesData = [];
        let obj = {
          startTime: this.value1[0],
          endTime: this.value1[1],
          type: this.switchValue ? "project" : "user",
          deptId: this.deptIds,
        };
        getChartsData(obj).then((res) => {
          if (res.success && res.data.length) {
            res.data.forEach((item) => {
              this.chartsXdata.push(
                item.user_nick ? item.user_nick : item.projects_name
              );
              this.seriesData.push(item.total_amount);
            });
          } else {
            this.$message({
              message: "暂无数据",
            });
          }
          this.drawColumn();
        });
      } else {
        this.$message({
          message: "请选择日期范围",
          type: "error",
        });
      }
    },

    drawColumn() {
      // 基于准备好的dom，初始化echarts实例
      let myChart = this.$echarts.init(this.$refs.myChart);
      // 绘制图表
      myChart.setOption({
        tooltip: { trigger: "axis" },
        grid: {
          left: "5%",
          right: "6%",
          bottom: "10%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: this.chartsXdata,
        },
        yAxis: {
          type: "value",
        },
        title: {
          // title为标题部分，有一级标题text，二级标题subtext。这里我们使用二级标题，再修改一下这个二级标题的位置即可出现我们想要的效果了，当然样式也可以通过title.subtextStyle去配置
          subtext: "单位（小时）",
          left: 24, // 距离左边位置
          top: 16, // 距离上面位置
        },
        dataZoom: [
          {
            type: "slider", // 在底部
            show: true, // 是否显示 组件。如果设置为 false，不会显示，但是数据过滤的功能还存在。
            start: 60, // 数据窗口范围的起始百分比。范围是：0 ~ 100。表示 0% ~ 100%。
            end: 3, // 数据窗口范围的结束百分比。范围是：0 ~ 100。
            bottom: 25, // 控制滚动条距离底部的位置;
            xAxisIndex: [0],
          },
        ],
        series: [
          {
            data: this.seriesData,
            type: "bar",
            barMaxWidth: 100,
            itemStyle: {
              normal: {
                color: "#5470c6",
              },
            },
          },
        ],
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.filter-container {
  display: flex;
  justify-content: space-between;
}

.collect-chart {
  display: flex;
}
</style>